﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data.Odbc; 
using WLMCoreLibrary;
using MiWebSite_Core;
using System.Web;
using System.Xml.Serialization;

namespace MWS_AddDirectory
{
    public class Cliente : BaseClass
    {
        #region private fields
        protected String _email;
        protected String _password;
        protected String _salt;
        protected String _Nombre;
        protected String _Apellidos;
        protected DateTime _FechaUltimoPago;
        protected String _preguntaSecreta;
        protected String _respuestaSecreta;
        protected String _Direccion;
        protected String _Colonia;
        protected String _Municipio;
        protected String _Estado;
        protected String _CP;
        protected String _RFC;
        protected String _RazonSocial;
        protected String _Telefono;
        protected String _Fax;
        protected String _Celular;
        protected String _EmailAlterno;
        protected String _DatoTemporal;
 
        #endregion

        #region public properties
        [XmlAttribute()]
        public String email {get;set; }
        [XmlIgnore()]
        public String password {get;set; }
        [XmlIgnore()]
        public String salt {get;set; }
        [XmlAttribute()]
        public String Nombre {get;set; }
        [XmlAttribute()]
        public String Apellidos {get;set; }
        [XmlAttribute()]
        public DateTime FechaUltimoPago {get;set; }
        [XmlAttribute()]
        public String preguntaSecreta {get;set; }
        [XmlAttribute()]
        public String respuestaSecreta {get;set; }
        [XmlAttribute()]
        public String Direccion {get;set; }
        [XmlAttribute()]
        public String Colonia {get;set; }
        [XmlAttribute()]
        public String Municipio {get;set; }
        [XmlAttribute()]
        public String Estado {get;set; }
        [XmlAttribute()]
        public String CP {get;set; }
        [XmlAttribute()]
        public String RFC {get;set; }
        [XmlAttribute()]
        public String RazonSocial {get;set; }
        [XmlAttribute()]
        public String Telefono {get;set; }
        [XmlAttribute()]
        public String Fax {get;set; }
        [XmlAttribute()]
        public String Celular {get;set; }
        [XmlAttribute()]
        public String EmailAlterno {get;set; }
        [XmlAttribute()]
        public String DatoTemporal
        {
           get;set;
       
        }
        #endregion

        #region constructors
        public Cliente()
        {
        }
        public Cliente(ref dbConnector ConexionDB)
        {
            ConexionDBInterna = ConexionDB;
            WLMClassBinder classBinder = new WLMClassBinder(ref ConexionDB);
            id = classBinder.NewRecord("CLIENTES");
            string queryString = "";
            queryString = "SELECT * FROM CLIENTES WHERE id='" + id + "'";
            GetRecord(queryString);
        }

        public Cliente(int registryId, ref dbConnector ConexionDB)
        {
            ConexionDBInterna = ConexionDB;
            string queryString = "";
            queryString = "SELECT * FROM CLIENTES WHERE id='" + registryId + "'";
            this.GetRecord(queryString);
        }

        public Cliente(string email, ref dbConnector ConexionDB)
        {
            ConexionDBInterna = ConexionDB;
            string queryString = "";
            queryString = "SELECT * FROM CLIENTES WHERE email='" + email + "'";
            this.GetRecord(queryString);
        }
        #endregion

        #region public methods
        public bool CheckUserPassword(string TryPassword)
        {
            SaltedHash encriptador = new SaltedHash();
            return encriptador.VerifyHashString(TryPassword, password, salt);
        }

        public string EnviarEmailNuevaCuenta(string newPassword)
        {
            DatoTemporal = newPassword;
            string cuerpoEmail = WLMFunctions.TransformXML(this, "http://www." + DeCurrentDomain.DomainName + "/xsl/Templates/Clientes/NewAccount.xslt",FuncionesDirectorio.GetTransformationParameters());

            return FuncionesDirectorio.EnviarEmail("info@" + DeCurrentDomain.DomainName, "Directorio de " + DeCurrentDomain.Ciudad, email, Nombre + " " + Apellidos, "Nueva Cuenta de Usuario en " + DeCurrentDomain.DomainName, cuerpoEmail);
        
        }

        public string EnviarEmailActualizacionCuenta()
        {
            string cuerpoEmail = WLMFunctions.TransformXML(this, "http://www." + DeCurrentDomain.DomainName + "/xsl/Templates/Clientes/AccoutUpdate.xslt",FuncionesDirectorio.GetTransformationParameters());

            return FuncionesDirectorio.EnviarEmail("info@" + DeCurrentDomain.DomainName, "Directorio de " + DeCurrentDomain.Ciudad, email, Nombre + " " + Apellidos, "Cuenta Actualizada " + DeCurrentDomain.DomainName, cuerpoEmail);

        }

        public string EnviarEmailRecuperacionPassword(string newPassword)
        {
            DatoTemporal = newPassword;
            
            string cuerpoEmail = WLMFunctions.TransformXML(this, "http://www." + DeCurrentDomain.DomainName + "/xsl/Templates/Clientes/NewPassword.xslt",FuncionesDirectorio.GetTransformationParameters());
            return FuncionesDirectorio.EnviarEmail("info@" + DeCurrentDomain.DomainName, "Directorio de " + DeCurrentDomain.Ciudad, email, Nombre + " " + Apellidos, "Nuevo password de su cuenta en " + DeCurrentDomain.DomainName, cuerpoEmail);

        }

        public void Delete()
        {
            string queryString = "";
            queryString = "DELETE FROM CLIENTES WHERE id='" + id + "'";
            ConexionDBInterna.ExecuteCommand(queryString);

        }
        #endregion

        #region Private Methods
        private void GetRecord(string queryString)
        {
            OdbcDataReader reader = ConexionDBInterna.ExecuteReader(queryString);
            if (reader.HasRows)
            {
                if (!reader.IsDBNull(reader.GetOrdinal("id")))
                    id = (System.Int32)reader["id"];
                if (!reader.IsDBNull(reader.GetOrdinal("fechaCreacion")))
                    fechaCreacion = Convert.ToDateTime(reader["fechaCreacion"]);  if (!reader.IsDBNull(reader.GetOrdinal("fechaModificacion"))) fechaModificacion = Convert.ToDateTime(reader["fechaModificacion"]); if (!reader.IsDBNull(reader.GetOrdinal("idUsuarioModificacion"))) idUsuarioModificacion = (System.Int32)reader["idUsuarioModificacion"];
                
                    
                if (!reader.IsDBNull(reader.GetOrdinal("idUsuario")))
                    idUsuario = (System.Int32)reader["idUsuario"];
                if (!reader.IsDBNull(reader.GetOrdinal("email")))
                    email = (System.String)reader["email"];
                if (!reader.IsDBNull(reader.GetOrdinal("password")))
                    password = (System.String)reader["password"];
                if (!reader.IsDBNull(reader.GetOrdinal("salt")))
                    salt = (System.String)reader["salt"];
                if (!reader.IsDBNull(reader.GetOrdinal("Nombre")))
                    Nombre = (System.String)reader["Nombre"];
                if (!reader.IsDBNull(reader.GetOrdinal("Apellidos")))
                    Apellidos = (System.String)reader["Apellidos"];
                if (!reader.IsDBNull(reader.GetOrdinal("FechaUltimoPago")))
                    FechaUltimoPago = Convert.ToDateTime(reader["FechaUltimoPago"]);
                if (!reader.IsDBNull(reader.GetOrdinal("preguntaSecreta")))
                    preguntaSecreta = (System.String)reader["preguntaSecreta"];
                if (!reader.IsDBNull(reader.GetOrdinal("respuestaSecreta")))
                    respuestaSecreta = (System.String)reader["respuestaSecreta"];
                if (!reader.IsDBNull(reader.GetOrdinal("Direccion")))
                    Direccion = (System.String)reader["Direccion"];
                if (!reader.IsDBNull(reader.GetOrdinal("Colonia")))
                    Colonia = (System.String)reader["Colonia"];
                if (!reader.IsDBNull(reader.GetOrdinal("Municipio")))
                    Municipio = (System.String)reader["Municipio"];
                if (!reader.IsDBNull(reader.GetOrdinal("Estado")))
                    Estado = (System.String)reader["Estado"];
                if (!reader.IsDBNull(reader.GetOrdinal("CP")))
                    CP = (System.String)reader["CP"];
                if (!reader.IsDBNull(reader.GetOrdinal("RFC")))
                    RFC = (System.String)reader["RFC"];
                if (!reader.IsDBNull(reader.GetOrdinal("RazonSocial")))
                    RazonSocial = (System.String)reader["RazonSocial"];
                if (!reader.IsDBNull(reader.GetOrdinal("Telefono")))
                    Telefono = (System.String)reader["Telefono"];
                if (!reader.IsDBNull(reader.GetOrdinal("Fax")))
                    Fax = (System.String)reader["Fax"];
                if (!reader.IsDBNull(reader.GetOrdinal("Celular")))
                    Celular = (System.String)reader["Celular"];
                if (!reader.IsDBNull(reader.GetOrdinal("EmailAlterno")))
                    EmailAlterno = (System.String)reader["EmailAlterno"];
            }
        }

        protected override void UpdateBind()
        {
            StringBuilder strCommand = new StringBuilder();
            strCommand.Append("UPDATE CLIENTES set "); strCommand.Append("fechaModificacion='" + this.fechaModificacion.ToString("yyyy-MM-dd HH:mm:ss") + "'"); strCommand.Append(",idUsuarioModificacion=\"" + idUsuarioModificacion.ToString() + "\"");
            
            strCommand.Append(",email=\"" + WLMFunctions.comillas(email) + "\"");
            strCommand.Append(",password=\"" + WLMFunctions.comillas(password) + "\"");
            strCommand.Append(",salt=\"" + WLMFunctions.comillas(salt) + "\"");
            strCommand.Append(",Nombre=\"" + WLMFunctions.comillas(Nombre) + "\"");
            strCommand.Append(",Apellidos=\"" + WLMFunctions.comillas(Apellidos) + "\"");
            strCommand.Append(",FechaUltimoPago='" + FechaUltimoPago.ToString("yyyy-MM-dd HH:mm:ss") + "'");
            strCommand.Append(",preguntaSecreta=\"" + WLMFunctions.comillas(preguntaSecreta) + "\"");
            strCommand.Append(",respuestaSecreta=\"" + WLMFunctions.comillas(respuestaSecreta) + "\"");
            strCommand.Append(",Direccion=\"" + WLMFunctions.comillas(Direccion) + "\"");
            strCommand.Append(",Colonia=\"" + WLMFunctions.comillas(Colonia) + "\"");
            strCommand.Append(",Municipio=\"" + WLMFunctions.comillas(Municipio) + "\"");
            strCommand.Append(",Estado=\"" + WLMFunctions.comillas(Estado) + "\"");
            strCommand.Append(",CP=\"" + WLMFunctions.comillas(CP) + "\"");
            strCommand.Append(",RFC=\"" + WLMFunctions.comillas(RFC) + "\"");
            strCommand.Append(",RazonSocial=\"" + WLMFunctions.comillas(RazonSocial) + "\"");
            strCommand.Append(",Telefono=\"" + WLMFunctions.comillas(Telefono) + "\"");
            strCommand.Append(",Fax=\"" + WLMFunctions.comillas(Fax) + "\"");
            strCommand.Append(",Celular=\"" + WLMFunctions.comillas(Celular) + "\"");
            strCommand.Append(",EmailAlterno=\"" + WLMFunctions.comillas(EmailAlterno) + "\"");
            strCommand.Append(" WHERE id='" + id + "'");
            ConexionDBInterna.ExecuteCommand(strCommand.ToString());
        }
        #endregion

        internal void nuevoMetodoNecesario(string p)
        {
            throw new NotImplementedException();
        }
    }

    public class ClientesCollection
    {
        
        private List<Cliente> _items;
        public List<Cliente> Elementos {get;set; }
        public ClientesCollection()
        {
        }
        public ClientesCollection(ref dbConnector ConexionDB)
        {
            
            string strCommand = "SELECT id FROM CLIENTES ";
            OdbcDataReader dataReader = ConexionDB.ExecuteReader(strCommand);
            Elementos = new List<Cliente>();
            while (dataReader.Read())
            {
                Cliente newItem = new Cliente(Convert.ToInt32(dataReader["id"]),ref ConexionDB);
                Elementos.Add(newItem);
            }
            dataReader.Close();
            dataReader.Dispose();
        }
    }

    public class CurrentClient
    {
        public static void LogOut()
        {
            HttpContext.Current.Session.Remove("idCliente");
            HttpContext.Current.Session.Remove("nombreCliente");
            HttpContext.Current.Session.Remove("emailCliente");
            HttpContext.Current.Response.Redirect("/");
        }

        public static int Id
        {
            get
            {
                if (HttpContext.Current.Session["idCliente"] != null)
                    return Convert.ToInt32(HttpContext.Current.Session["idCliente"]);

                else
                    return 0;
            }
            
        }

        public static string Nombre
        {
            get
            {
                if (HttpContext.Current.Session["nombreCliente"] != null)
                    return HttpContext.Current.Session["nombreCliente"].ToString();
                else
                    return "";
            }
            
        }

        public static string Email
        {
            get
            {
                if (HttpContext.Current.Session["emailCliente"] != null)
                    return HttpContext.Current.Session["emailCliente"].ToString();
                else
                    return "";
            }
            
        }

        public static void ClientLogin(Cliente cliente)
        {
            HttpContext.Current.Session.Add("idCliente",cliente.id);
            HttpContext.Current.Session.Add("nombreCliente", cliente.Nombre);
            HttpContext.Current.Session.Add("emailCliente", cliente.email);
        }
    }

    public class ClientesProspecto : BaseClass
    {
        #region private fields
        private String _email;
        private String _Nombre;
        private String _Apellidos;
        private String _Direccion;
        private String _Colonia;
        private String _Municipio;
        private String _Estado;
        private String _CP;
        private String _RFC;
        private String _RazonSocial;
        private String _Telefono;
        private String _Comentarios;
        #endregion

        #region public properties
        public String email {get;set; }
        public String Nombre {get;set; }
        public String Apellidos {get;set; }
        public String Direccion {get;set; }
        public String Colonia {get;set; }
        public String Municipio {get;set; }
        public String Estado {get;set; }
        public String CP {get;set; }
        public String RFC {get;set; }
        public String RazonSocial {get;set; }
        public String Telefono {get;set; }
        public String Comentarios {get;set; }
        #endregion

        #region constructors
        public ClientesProspecto(ref dbConnector ConexionDB)
        {
            
            WLMClassBinder classBinder = new WLMClassBinder(ref ConexionDB);
            id = classBinder.NewRecord("CLIENTESPROSPECTO");
            string queryString = "";
            queryString = "SELECT * FROM CLIENTESPROSPECTO WHERE id='" + id + "'";
            GetRecord(queryString);
        }

        public ClientesProspecto(int registryId, ref dbConnector ConexionDB)
        {
            
            string queryString = "";
            queryString = "SELECT * FROM CLIENTESPROSPECTO WHERE id='" + registryId + "'";
            WLMClassBinder classBinder = new WLMClassBinder(ref ConexionDB);
            this.GetRecord(queryString);
        }
        #endregion

        #region public methods
        
        public void Delete()
        {
            string queryString = "";
            queryString = "DELETE FROM CLIENTESPROSPECTO WHERE id='" + id + "'";
            ConexionDBInterna.ExecuteCommand(queryString);

        }

        public string LlenadoEmailContacto()
        {
            string email1 = "";// MiWebSiteFunctions.LoadTemplate("ContenedorEmail.htm");
            string email2 = "";// MiWebSiteFunctions.LoadTemplate("EmailProspecto.htm");
            email1 = email1.Replace("{CONTENIDOEMAIL}", email2);
            email1 = email1.Replace("{DOMINIO}", DeCurrentDomain.DomainName);
            email1 = email1.Replace("{NOMBREDOMINIO2}", DeCurrentDomain.DomainName.Substring(2));
            email1 = email1.Replace("{NOMBRE}", Nombre+ " " + Apellidos);
            email1 = email1.Replace("{EMAIL}", email);
            email1 = email1.Replace("{RFC}", RFC);
            email1 = email1.Replace("{TELEFONO}", Telefono );
            email1 = email1.Replace("{NOMBRENEGOCIO}", RazonSocial );
            email1 = email1.Replace("{DIRECCION}",Direccion );
            email1 = email1.Replace("{COLONIA}", Colonia);
            email1 = email1.Replace("{MUNICIPIO}",Municipio );
            email1 = email1.Replace("{ESTADO}", Estado);
            email1 = email1.Replace("{CP}", CP);
            email1 = email1.Replace("{COMENTARIOS}",Comentarios.Replace("\n","<br/>") );

            return email1;
        }
        #endregion

        #region Private Methods
        private void GetRecord(string queryString)
        {
            OdbcDataReader reader = ConexionDBInterna.ExecuteReader(queryString);
            if (reader.HasRows)
            {
                if (!reader.IsDBNull(reader.GetOrdinal("id")))
                    id = (System.Int32)reader["id"];
                if (!reader.IsDBNull(reader.GetOrdinal("fechaCreacion")))
                    fechaCreacion = Convert.ToDateTime(reader["fechaCreacion"]);  if (!reader.IsDBNull(reader.GetOrdinal("fechaModificacion"))) fechaModificacion = Convert.ToDateTime(reader["fechaModificacion"]); if (!reader.IsDBNull(reader.GetOrdinal("idUsuarioModificacion"))) idUsuarioModificacion = (System.Int32)reader["idUsuarioModificacion"];
                
                    
                if (!reader.IsDBNull(reader.GetOrdinal("idUsuario")))
                    idUsuario = (System.Int32)reader["idUsuario"];
                if (!reader.IsDBNull(reader.GetOrdinal("email")))
                    email = (System.String)reader["email"];
                if (!reader.IsDBNull(reader.GetOrdinal("Nombre")))
                    Nombre = (System.String)reader["Nombre"];
                if (!reader.IsDBNull(reader.GetOrdinal("Apellidos")))
                    Apellidos = (System.String)reader["Apellidos"];
                if (!reader.IsDBNull(reader.GetOrdinal("Direccion")))
                    Direccion = (System.String)reader["Direccion"];
                if (!reader.IsDBNull(reader.GetOrdinal("Colonia")))
                    Colonia = (System.String)reader["Colonia"];
                if (!reader.IsDBNull(reader.GetOrdinal("Municipio")))
                    Municipio = (System.String)reader["Municipio"];
                if (!reader.IsDBNull(reader.GetOrdinal("Estado")))
                    Estado = (System.String)reader["Estado"];
                if (!reader.IsDBNull(reader.GetOrdinal("CP")))
                    CP = (System.String)reader["CP"];
                if (!reader.IsDBNull(reader.GetOrdinal("RFC")))
                    RFC = (System.String)reader["RFC"];
                if (!reader.IsDBNull(reader.GetOrdinal("RazonSocial")))
                    RazonSocial = (System.String)reader["RazonSocial"];
                if (!reader.IsDBNull(reader.GetOrdinal("Telefono")))
                    Telefono = (System.String)reader["Telefono"];
                if (!reader.IsDBNull(reader.GetOrdinal("Comentarios")))
                    Comentarios = (System.String)reader["Comentarios"];
            }
        }

        protected override void UpdateBind()
        {
            StringBuilder strCommand = new StringBuilder();
            strCommand.Append("UPDATE CLIENTESPROSPECTO set "); strCommand.Append("fechaModificacion='" + this.fechaModificacion.ToString("yyyy-MM-dd HH:mm:ss") + "'"); strCommand.Append(",idUsuarioModificacion=\"" + idUsuarioModificacion.ToString() + "\"");
            
            strCommand.Append(",email=\"" + WLMFunctions.comillas(email) + "\"");
            strCommand.Append(",Nombre=\"" + WLMFunctions.comillas(Nombre) + "\"");
            strCommand.Append(",Apellidos=\"" + WLMFunctions.comillas(Apellidos) + "\"");
            strCommand.Append(",Direccion=\"" + WLMFunctions.comillas(Direccion) + "\"");
            strCommand.Append(",Colonia=\"" + WLMFunctions.comillas(Colonia) + "\"");
            strCommand.Append(",Municipio=\"" + WLMFunctions.comillas(Municipio) + "\"");
            strCommand.Append(",Estado=\"" + WLMFunctions.comillas(Estado) + "\"");
            strCommand.Append(",CP=\"" + WLMFunctions.comillas(CP) + "\"");
            strCommand.Append(",RFC=\"" + WLMFunctions.comillas(RFC) + "\"");
            strCommand.Append(",RazonSocial=\"" + WLMFunctions.comillas(RazonSocial) + "\"");
            strCommand.Append(",Telefono=\"" + WLMFunctions.comillas(Telefono) + "\"");
            strCommand.Append(",Comentarios=\"" + WLMFunctions.comillas(Comentarios) + "\"");
            strCommand.Append(" WHERE id='" + id + "'");
            ConexionDBInterna.ExecuteCommand(strCommand.ToString());
        }
        #endregion
    }

    public class ClientesProspectoCollection
    {
    
        public List<ClientesProspecto> Items {get;set; }
        public ClientesProspectoCollection()
        {
        }

        public ClientesProspectoCollection(ref dbConnector ConexionDB)
        {
            
            string strCommand = "SELECT id FROM CLIENTESPROSPECTO ";
            OdbcDataReader dataReader = ConexionDB.ExecuteReader(strCommand);
           
            while (dataReader.Read())
            {
                ClientesProspecto newItem = new ClientesProspecto(Convert.ToInt32(dataReader["id"]),ref ConexionDB);
                Items.Add(newItem);
            }
            dataReader.Close();
            dataReader.Dispose();
        }
    }
}
